package warehouse;

import java.sql.*;

public class DatabaseBean {
	private Connection conn = null;
	private Statement stmt = null;
	
	public DatabaseBean() {
		this.conn = connect();//连接数据库
	}
	
	
	public static Connection connect() {
		Connection conn = null;
		String driverName = "com.mysql.cj.jdbc.Driver";
		String dbname = "warehouse";
		String url = "jdbc:mysql://localhost:3306/"+dbname+"?&serverTimezone=GMT%2B8&useSSL=false";
		String username="root";
		String password="1234";
		
		try
		{
			Class.forName(driverName);	
			System.out.println("加载成功");
		}catch(ClassNotFoundException e)
		{
			System.out.print("Error loading Driver,不能加载驱动程序！");
		}
		
		try
		{
			conn = DriverManager.getConnection(url,username,password);
		}
		catch(SQLException er)
		{
			System.out.print("Error getConnection,不能连接数据库！");
		}
		return conn;
	}
	
	/**
	 * 执行查询操作
	 * @param sql
	 * @return 查询结果集ResultSet对象
	 */
	public ResultSet executeQuery(String sql)
	{
		//TODO
		ResultSet rs = null;
		try
		{
			stmt=conn.createStatement();	//建立Statement对象
			rs=stmt.executeQuery(sql);		//执行SQL语句
			
		}
		catch(SQLException ex)
		{
			System.err.print("Error Execute Query:"+ex.getMessage());
		}
		return rs;
	}
	
	/**
	 * 执行增删改查
	 * @param sql
	 */
	public boolean executeUpdate(String sql) {
		//TODO
		try
		{
			stmt=conn.createStatement();	//建立Statement对象
			stmt.executeUpdate(sql);			//执行SQL语句
			
		}
		catch(SQLException ex)
		{
			System.err.println(ex.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * 关闭各种资源
	 */
	public void close() {
		//TODO
		try
		{
			if(stmt!=null) stmt.close();
			if(conn!=null) conn.close();
		}
		catch(SQLException ex){
			System.err.println(ex.getMessage());
		}
	}
	
	
	
	
	
	
	
	
	
	
	//---------------------
	public Connection getConn() {
		return conn;
	}
	public void setConn(Connection conn) {
		this.conn = conn;
	}
	public Statement getStmt() {
		return stmt;
	}
	public void setStmt(Statement stmt) {
		this.stmt = stmt;
	}
	
	
}
